<template>
  <van-form ref="AppForm" class="full-width full-height column justify-between text-left " @blur="$emit('blur')"
            @submit="onSubmit">

    <div class="q-px-md">
      <template v-for="formItem in formItems" :key="formItem.name">
        <div v-show="showOn(formItem)">
          <div :class="formItem.required?'required':''" class="text-info q-py-sm">
            {{ formItem.label }}
          </div>
          <!--        用户名-->
          <van-field v-if="formItem.type==='username'" v-model="formData[formItem.field]"
                     :rules="formItem.rules" class="bg-secondary inputRadius" right-icon="arrow-down"
                     size="large"
                     @blur="onBlur"
                     @focus="onFocus"
                     @click-right-icon="clickRightIcon(formItem,formData)">
          </van-field>
          <!-- 输入手机号，调起手机号键盘 -->
          <van-field v-else-if="formItem.type==='phone'" v-model="formData[formItem.field]" :rules="formItem.rules"
                     class="bg-secondary inputRadius " size="large" type="tel"
                     @blur="onBlur"
                     @focus="onFocus" />
          <!-- 允许输入正整数，调起纯数字键盘 -->
          <van-field v-else-if="formItem.type==='digit'" v-model="formData[formItem.field]"
                     :rules="formItem.rules" class="bg-secondary inputRadius" size="large"
                     type="digit"
                     @blur="onBlur"
                     @focus="onFocus" />
          <!-- 允许输入数字，调起带符号的纯数字键盘 -->
          <van-field v-else-if="formItem.type==='number'" v-model="formData[formItem.field]"
                     :rules="formItem.rules" class="bg-secondary inputRadius" size="large"
                     type="number"
                     @blur="onBlur"
                     @focus="onFocus" />
          <!-- 输入密码 -->
          <van-field v-else-if="formItem.type==='validationCode'" v-model="formData[formItem.field]"
                     :rules="formItem.rules" class="bg-secondary inputRadius" size="large"
                     type="number"
                     @blur="onBlur"
                     @focus="onFocus">
            <template #button>
              <van-button :disabled="Timer>0" class="bg-info text-white no-border text-size-14" size="small"
                          style="min-width: 70px" type="primary" @click="getCode(formItem)">{{
                  (Timer ? "ResendIn" + "   " + Timer + "   " + "秒" : "getCode")
                }}
              </van-button>
            </template>
          </van-field>
          <!--        输入验证码-->
          <van-field v-else-if="formItem.type==='password'" v-model="formData[formItem.field]" :rules="formItem.rules"
                     :type="formItem.showPassword?'text':'password'" autocomplete="false"
                     class="bg-secondary inputRadius"
                     size="large" @blur="onBlur"
                     @focus="onFocus">
            <template #right-icon>
              <van-icon :name="formItem.showPassword?'eye-o':'eye'"
                        @click="formItem.showPassword=!formItem.showPassword" />
            </template>
          </van-field>
          <!--选择字段-->
          <template v-else-if="formItem.type==='select'">
            <van-field
              v-model="formData[formItem.field]"
              :placeholder="`选择${formItem.label}`"
              class="bg-secondary inputRadius" is-link
              readonly size="large" @blur="onBlur"
              @click="showPickerFun(formItem)"
              @focus="onFocus"
            />
          </template>
          <!--        带图标的选择-->
          <template v-else-if="formItem.type==='imgSelect'">
            <van-field
              v-model="none"
              class="bg-secondary inputRadius"
              is-link readonly
              size="large"
              @click="showPickerFun(formItem)"
            >
              <template v-slot:input>
                <i :class="formData[formItem.field]" class="iconfont text-primary text-size-14 text-bold" />
              </template>
            </van-field>
          </template>
          <!--        日期选择-->
          <template v-else-if="formItem.type==='timePicker'">
            <van-field
              v-model="formData[formItem.field]"
              class="bg-secondary inputRadius"
              is-link readonly
              size="large"
              @click="formItem.show=true"
            >
            </van-field>
            <van-calendar :min-date="minDate" :max-date="maxDate" v-model:show="formItem.show" @confirm="val=>selectDate(val,formItem)" />

          </template>
          <!--radio-->
          <van-field v-else-if="formItem.type==='switch'" autocomplete="false" class="bg-secondary inputRadius"
                     name="switch" size="large">
            <template #input>
              <van-switch v-model="formData[formItem.field]" size="20px" />
            </template>
          </van-field>
          <!-- 输入任意文本 -->
          <van-field v-else v-model="formData[formItem.field]" :readonly="formItem.readonly&&formItem.readonly()"
                     :rules="formItem.rules" class="bg-secondary inputRadius" size="large"
                     @blur.stop="onBlur"
                     @focus.stop="onFocus" />

        </div>
      </template>


      <van-popup v-model:show="showPicker" position="bottom" round>
        <van-picker v-show="currentPopupFormItem.type==='imgSelect'"
                    :columns="pickerOption"
                    @cancel="showPicker = false"
                    @confirm="onConfirm">
          <template #option="option">
            <div>
              <i :class="option.value" class="iconfont text-primary text-size-16 text-bold q-mr-xs" />
              {{ option.text }}
            </div>

          </template>
        </van-picker>
        <van-picker v-show="currentPopupFormItem.type!=='imgSelect'"
                    :columns="pickerOption"
                    @cancel="showPicker = false"
                    @confirm="onConfirm" />
      </van-popup>
    </div>


    <div v-if="buttonName" class="q-pa-md q-mt-lg">
      <van-button class="full-width bg-primary text-white text-size-18 no-border" native-type="submit" size="normal">
        {{ buttonName }}
      </van-button>
    </div>


  </van-form>


</template>

<script>
import { computed, ref, watch } from "vue";
import { formatDate } from "@/assets/ts/publicUtil";

export default {
  name: "AppForm",
  props: {
    formItems: {
      type: Array,
      default: () => [],
      require: true
    },
    buttonName: {
      type: String,
      require: false
    },
    currentData: {
      type: Object,
      default: () => {
      }
    }
  },
  setup(props, { emit }) {
    const Timer = ref(0);
    const formData = ref(JSON.parse(JSON.stringify(props.currentData)));
    watch(() => props.currentData, (n) => {
      if (n) formData.value = n;
    });

    const showOn = computed(() => {
      return (formItem) => {
        return !formItem.showOn || (formItem.showOn && formItem.showOn(formData.value));
      };
    });

    async function getCode(formItem) {
      let result = await formItem.getCode(formData.value);
      if (!result) {
        return;
      }
      //间隔时间
      Timer.value = 60;
      let Interval =
        setInterval(() => {
          if (Timer.value > 0) {
            Timer.value--;
          } else {
            Interval && clearTimeout(Interval);
          }
        }, 1000);
    }

    // 同步数据过去
    // const emit = defineEmits(["update:currentData"]);
    watch(formData.value, (n) => {
      // console.log(o)
      emit("update:currentData", n);
    });


    function selectDate(val, formItems) {
      formData.value[formItems.field] = formatDate(val, formItems.dateType);
      formItems.show = false;
    }

    return {
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(),
      selectDate,

      showOn,
      formData,
      Timer, getCode,
      none: "",
      showPicker: ref(false),
      pickerOption: ref([]),
      currentPopupFormItem: ref({})
    };
  },

  methods: {
    clickRightIcon(formItem, formData) {
      formItem.clickRightIcon && formItem.clickRightIcon.bind(this)(formItem, formData);
    },
    showPickerFun(formItem) {
      this.currentPopupFormItem = formItem || {};
      if (formItem.option && formItem.option.length > 0) {
        this.pickerOption = formItem.option;
        this.showPicker = true;
      } else if (formItem.optionFun) {
        formItem.optionFun(formItem, (option) => {
          this.pickerOption = option;
          this.showPicker = true;
        });
      }

    },
    onConfirm(val) {

      const formItem = this.currentPopupFormItem;

      if (formItem.onConfirm) {
        formItem.onConfirm(val, formItem);
      } else if (formItem.props) {
        this.formData[formItem.props.label] = val.text;
        this.formData[formItem.props.value] = val.value;
      } else {
        this.formData[formItem.field] = val.value;
      }
      this.showPicker = false;
    },
    onSubmit() {
      this.$emit("onSubmit", this.formData);
    },
    onBlur() {
      console.log("onBlur");
      this.$emit("onBlur");
    },
    onFocus() {
      console.log("onFocus");

      this.$emit("onFocus");
    }
  }
};
</script>

<style scoped>
.inputRadius {
  border-radius: 10px;
}
</style>
